//
//  CZMyTaskSubViewController.m
//  nsj_iOS
//
//  Created by apple on 2017/1/24.
//  Copyright © 2017年 GCZ. All rights reserved.
//

#import "CZMyTaskSubViewController.h"
#import "CZMyTaskCell.h"
#import "CZMyTaskDetailViewController.h"

static NSString *const my_subtask_cell = @"my_subtask_cell";
@interface CZMyTaskSubViewController () <UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *taskSubTableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) LGRefreshView *refreshView;
@property (nonatomic, assign) NSInteger currentPage;

@end

@implementation CZMyTaskSubViewController

- (NSMutableArray *__nonnull)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(getData) name:CZLoginSuccessNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(removedata) name:CZLogoutNotification object:nil];
    _currentPage = 1;
    _taskSubTableView.estimatedRowHeight = 75;
    _taskSubTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_taskSubTableView registerNib:[UINib nibWithNibName:@"CZMyTaskCell" bundle:nil] forCellReuseIdentifier:my_subtask_cell];
    _refreshView = [LGRefreshView refreshViewWithScrollView:self.taskSubTableView
                                             refreshHandler:^(LGRefreshView *refreshView){
                                                 [self.taskSubTableView.mj_footer setState:(MJRefreshStateIdle)];
                                                 _currentPage = 1;
                                                 [self postMyTaskDataWithStatus:self.status];
                                             }];
    _refreshView.center = CGPointMake(Main_Screen_Width / 2, _refreshView.center.y);
    _refreshView.tintColor = ThemeColor;
    _refreshView.backgroundColor = [UIColor clearColor];
    
    self.taskSubTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _currentPage ++;
        [self postMyTaskDataWithStatus:self.status];
    }];
    
    // Do any additional setup after loading the view from its nib.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    self.taskSubTableView.mj_footer.hidden = self.dataArray.count == 0 ? YES : NO;
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CZMyTaskCell *cell = [tableView dequeueReusableCellWithIdentifier:my_subtask_cell];
    
    NSDictionary *dic = self.dataArray[indexPath.row];
    cell.taskTitleLabel.text = dic[@"task_name"];
    
    NSString *startTime = dic[@"start_date"];
    NSString *endTime = dic[@"end_date"];
    NSString *task_limit = dic[@"task_limit"];
    NSString *task_require = dic[@"task_require"];
    NSString *task_star = dic[@"task_star"];
    if (task_limit.integerValue < 100) {
        cell.taskLimitLabel.text = @"全员任务";
        cell.taskLimitImageView.image = [UIImage imageNamed:@"icon_nonmember"];
    } else {
        cell.taskLimitLabel.text = @"公民任务";
        cell.taskLimitImageView.image = [UIImage imageNamed:@"icon_member"];
    }
    NSString *dateTime = [[[startTime substringToIndex:10] stringByAppendingString:@"至"] stringByAppendingString:[endTime substringToIndex:10]];
    NSString *dateStr = [dateTime stringByAppendingString:[NSString stringWithFormat:@" 剩余%@天", dic[@"time_remine"]]];
    cell.taskDateLabel.text = dateStr;
    
    if (task_require.integerValue == 0) {
        //选做
        cell.taskRightImageView.image = [UIImage imageNamed:@"icon_option"];
        cell.taskRightLabel.text = @"选作任务";
        cell.taskRightLabel.textColor = mRGBColor(56, 137, 126);
    } else {
        //必做
        cell.taskRightImageView.image = [UIImage imageNamed:@"icon_must"];
        cell.taskRightLabel.text = @"必须任务";
        cell.taskRightLabel.textColor = mRGBColor(255, 195, 0);
    }
    NSArray *statusArr = @[@"进行中", @"已完成", @"已奖励", @"不通过", @"逾期"];
    NSArray *statusIcons = @[@"icon_progress", @"icon_done" , @"icon_gift", @"icon_cancel", @"icon_timeout"];
    NSString *status = dic[@"record_stauts"];
    cell.taskStatusImageView.image = [UIImage imageNamed:statusIcons[status.integerValue]];
    cell.taskStatusLabel.text = statusArr[status.integerValue];
    [cell setStarsWithNumber:task_star.integerValue];
    
    return cell;
}
- (void)getData {
    [self postMyTaskDataWithStatus:self.status];
}
- (void)removedata {
    [self.dataArray removeAllObjects];
    [self.taskSubTableView reloadData];
}
- (void)postMyTaskDataWithStatus:(NSNumber *)status {
    NSString *urlString = [NSString stringWithFormat:@"%@/api/web/index.php/v1/task/my-tasks",APP_HOST];
    [SVProgressHUD show];
    DLog(@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:User_Token]);
    if (![[NSUserDefaults standardUserDefaults] objectForKey:User_Token]) {
        [SVProgressHUD dismiss];
        CZBaseTabBarController *rootVC = (CZBaseTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        CZNavigationController *naviVC = rootVC.childViewControllers[0];
        CZMessionCenterViewController *homeVC = (CZMessionCenterViewController *)naviVC.childViewControllers[0];
        CZNavigationController *mineNC = rootVC.childViewControllers[4];
        CZMineViewController *mineVC = mineNC.childViewControllers[0];
        CZUserLoginViewController * loginVC = [[[CZNsjHelper alloc] init] presentLoginViewControllerWithViewCotroller:self.parentViewController];
        @weakify(mineVC);
        loginVC.callBack = ^(){
            [weak_mineVC getUserData];
            [homeVC setUserIconImage];
            weak_mineVC.userIconImageView.yy_imageURL = [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] objectForKey:User_Logo]];
            [self postMyTaskDataWithStatus:self.status];
        };
        return;
    }
    
    [GCZAFNetWorking POST:urlString params:@{@"token" : [[NSUserDefaults standardUserDefaults] objectForKey:User_Token], @"status" : self.status, @"page" : @(_currentPage)} success:^(id response) {
        [SVProgressHUD dismiss];
        if ([response[@"code"] isEqualToString:@"200"]) {
            NSArray *arr = response[@"result"];
            if (_currentPage == 1) {
                self.dataArray = arr.mutableCopy;
            } else {
                for (NSDictionary *dic in arr) {
                    [self.dataArray addObject:dic];
                }
            }
            [_refreshView endRefreshing];
            [self.taskSubTableView.mj_footer endRefreshing];
            [self.taskSubTableView reloadData];
            self.taskSubTableView.mj_footer.hidden = NO;
            [UIView animateWithDuration:0.2 animations:^{
                self.taskSubTableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
            }];
        } else if ([response[@"code"] isEqualToString:@"300"]) {
            [_refreshView endRefreshing];
            [self.taskSubTableView.mj_footer endRefreshingWithNoMoreData];
            [UIView animateWithDuration:0.2 animations:^{
                self.taskSubTableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
            }];
        } else if ([response[@"code"] isEqualToString:@"301"]) {
            
//            [self.dataArray removeAllObjects];
//            [self.taskSubTableView reloadData];
//            [SVProgressHUD showErrorWithStatus:response[@"message"]];
            [_refreshView endRefreshing];
            [self.taskSubTableView.mj_footer endRefreshingWithNoMoreData];
            [UIView animateWithDuration:0.2 animations:^{
                self.taskSubTableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
            }];
        } else if ([response[@"status"] isEqualToString:@"104"]) {
            [SVProgressHUD dismiss];
            CZBaseTabBarController *rootVC = (CZBaseTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
            CZNavigationController *naviVC = rootVC.childViewControllers[0];
            CZMessionCenterViewController *homeVC = (CZMessionCenterViewController *)naviVC.childViewControllers[0];
            CZNavigationController *mineNC = rootVC.childViewControllers[4];
            CZMineViewController *mineVC = mineNC.childViewControllers[0];
            CZUserLoginViewController * loginVC = [[[CZNsjHelper alloc] init] presentLoginViewControllerWithViewCotroller:self.parentViewController];
            @weakify(mineVC);
            loginVC.callBack = ^(){
                [weak_mineVC getUserData];
                [homeVC setUserIconImage];
                weak_mineVC.userIconImageView.yy_imageURL = [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] objectForKey:User_Logo]];
                [self postMyTaskDataWithStatus:self.status];
            };
            return;
        } else {
//            [SVProgressHUD showErrorWithStatus:response[@"message"]];
            [_refreshView endRefreshing];
            [self.taskSubTableView.mj_footer endRefreshing];
            [UIView animateWithDuration:0.2 animations:^{
                self.taskSubTableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
            }];
        }
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [_refreshView endRefreshing];
        [self.taskSubTableView.mj_footer endRefreshing];
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
    }];


}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    CZMyTaskDetailViewController *detailVC = [[CZMyTaskDetailViewController alloc] init];
    NSDictionary *dic = self.dataArray[indexPath.row];
    detailVC.record_id = dic[@"record_id"];
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
